package com.gc.baselib.base;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.gc.baselib.R;


/**
 * 基础Popwindow
 */
public abstract class BasePopWindow extends PopupWindow {
    protected BaseActivity baseActivity;
    protected View mPopView;
    public BasePopWindow(BaseActivity context) {
        super(context);
        this.baseActivity = context;
        init(context);
        initPopupWindow();
    }
    private void init(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        mPopView = inflater.inflate(getLayoutResId(), null);
        initView();
    }

    protected abstract void initView();


    protected abstract int getLayoutResId() ;
    private void initPopupWindow() {
        this.setContentView(mPopView);// 设置View
        this.setFocusable(true);// 设置弹出窗口可
        this.setOutsideTouchable(true);
        this.setBackgroundDrawable(new ColorDrawable(0x00000000));// 设置背景透明
        initPopSize();
        setAnimationStyle(getAnimationStyle());
    }
    private  float bgAlpha=0.5f;
    public BasePopWindow setBgAlpha(float bgAlpha){
        this.bgAlpha=bgAlpha;
        return this;
    }
    public  int getAnimationStyle(){
        return R.style.base_popup_anim;
    }
    public void initPopSize(){
        this.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);// 设置弹出窗口的宽
        this.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);// 设置弹出窗口的高
    }

    @Override
    public void dismiss() {
        backgroundAlpha(1.0f);//0.0-1.0
        super.dismiss();
    }

    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        backgroundAlpha(bgAlpha);
        super.showAtLocation(parent, gravity, x, y);
    }


    @Override
    public void showAsDropDown(View anchor) {
        backgroundAlpha(bgAlpha);
        super.showAsDropDown(anchor);
    }

    @Override
    public void showAsDropDown(View anchor, int xoff, int yoff) {
        backgroundAlpha(bgAlpha);
        super.showAsDropDown(anchor, xoff, yoff);
    }

    @Override
    public void showAsDropDown(View anchor, int xoff, int yoff, int gravity) {
        backgroundAlpha(bgAlpha);
        super.showAsDropDown(anchor, xoff, yoff, gravity);
    }

    /**
     * 设置添加屏幕的背景透明度(值越大,透明度越高)
     *
     * @param bgAlpha
     */
    private void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = baseActivity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        baseActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        baseActivity.getWindow().setAttributes(lp);
    }

}
